package com.example.springmvc_exception.通过接口实现全局异常;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
* 实现接口HandlerExceptionResolver定义全局异常
* */
@Component
public class GlobalException implements HandlerExceptionResolver {

    /*
    * 参数解释：
    * request
    * response
    * 异常处理的目标
    * 异常处理的类型
    * */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error");
        /*判断异常的分类*/
        if(ex instanceof RuntimeException){
            RuntimeException e=(RuntimeException)ex;
            System.out.println(e.getMessage());
            modelAndView.addObject("msg", e.getMessage());
        }
        return modelAndView;
    }
}